package ac.svn.accesscontrol.ui.window;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

import javax.swing.DefaultListModel;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;

import ac.svn.accesscontrol.store.IResources;
import ac.svn.accesscontrol.store.ISVNItem;
import ac.svn.accesscontrol.store.SVNGroup;
import ac.svn.accesscontrol.utils.UIUtility;
import ac.svn.accesscontrol.utils.Utility;

/**
 * @author ankush
 *
 */
public class GroupDetailsEditorWindow extends JDialog
{

	public static final int SAVE_OPTION 	= 1 ;
	public static final int CANCEL_OPTION 	= -1 ;

	private ISVNItem targetItem = null; 

	private int selectedOption = CANCEL_OPTION;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private JSplitPane splitPane;

	private JList allUsersList;
	private JList selectedUsersList;

	private JButton okButton;
	private JButton cancelButton;

	private JButton toLeftButton;
	private JButton toRightButton;

	private JPanel headerPanel; 
	private DefaultListModel availableCellModel;
	private DefaultListModel selectedCellModel;
	private JScrollPane availablePane;
	private JScrollPane selectedPane;
	private JLabel svnItemDescription;
	private JTextField groupNameText;
	private JPanel groupDetailsBasePanel;
	private JPanel groupAliasPanel;
	private JLabel lblNewLabel;
	private JTextField groupAliasText;
	private JScrollPane scrollPane;
	private JTextPane commentsText;
	public GroupDetailsEditorWindow()
	{
		super();
		setModal(true);
		initComponents();
	}

	private void initComponents() 
	{
		Color WHITE = Color.WHITE;
		Border border = UIUtility.setAllShadowedBorder(null);

		getContentPane().setLayout(new BorderLayout(5, 5));
		getContentPane().setBackground(WHITE);

		setSize(800,600);
		setLocation();
		setTitle("Group Details Editor");

		availableCellModel = new DefaultListModel();
		selectedCellModel  = new DefaultListModel();

		splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
		splitPane.setBackground(WHITE);
		splitPane.setBorder(new TitledBorder(border,"Membership Change"));
		allUsersList = new JList(availableCellModel);

		availablePane = new JScrollPane();
		availablePane.setBackground(WHITE);
		availablePane.setBorder(border);
		availablePane.setViewportView(allUsersList);

		JLabel columnHeader = (new JLabel("Available Users"));
		columnHeader.setBorder(border);
		availablePane.setColumnHeaderView(columnHeader);

		selectedUsersList = new JList(selectedCellModel);
		selectedUsersList.setBorder(border);

		selectedPane = new JScrollPane();
		selectedPane.setBackground(WHITE);
		selectedPane.setBorder(border);
		selectedPane.setViewportView(selectedUsersList);

		columnHeader = (new JLabel("Selected Users"));
		columnHeader.setBorder(border);
		selectedPane.setColumnHeaderView(columnHeader);

		splitPane.setLeftComponent(availablePane);
		splitPane.setRightComponent(selectedPane);

		okButton = new JButton("Finish");
		okButton.setMnemonic('F');

		cancelButton = new JButton("Cancel");
		cancelButton.setMnemonic('C');

		toLeftButton = new JButton("<<");
		toRightButton = new JButton(">>");

		JPanel panel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
		panel.setBackground(WHITE);
		panel.setBorder(border);

		JPanel jPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
		jPanel.setBackground(WHITE);


		jPanel.add(toLeftButton);
		jPanel.add(toRightButton);

		panel.add(jPanel);

		panel.add(okButton);
		panel.add(cancelButton);

		headerPanel = new JPanel((new BorderLayout(5, 5)),true);
		headerPanel.setBackground(WHITE);
		headerPanel.setBorder(new TitledBorder(border,"Group Details"));

		svnItemDescription = new JLabel("Select item from left to right!",JLabel.LEFT);
		svnItemDescription.setBorder(border);

		headerPanel.add(svnItemDescription,BorderLayout.NORTH);

		getContentPane().add(panel,BorderLayout.SOUTH);
		getContentPane().add(splitPane,BorderLayout.CENTER);
		getContentPane().add(headerPanel,BorderLayout.NORTH);

		groupDetailsBasePanel = new JPanel();
		groupDetailsBasePanel.setBackground(WHITE);
		headerPanel.add(groupDetailsBasePanel, BorderLayout.CENTER);
		groupDetailsBasePanel.setLayout(new GridLayout(2, 0, 0, 2));

		BorderLayout bl_groupNamePanel = new BorderLayout(0,0);

		JPanel groupNamePanel = new JPanel(bl_groupNamePanel);
		groupNamePanel.setBackground(WHITE);
		groupNamePanel.setBorder(border);

		groupDetailsBasePanel.add(groupNamePanel);
		groupNameText = new JTextField(10);
		groupNamePanel.add((new JLabel(" Group Name: ")),BorderLayout.WEST);
		groupNamePanel.add(groupNameText,BorderLayout.CENTER);
		groupNamePanel.setBorder(border);

		groupNamePanel.setBorder(border);

		groupAliasPanel = new JPanel();
		groupAliasPanel.setBackground(WHITE);
		groupAliasPanel.setBorder(border);

		groupDetailsBasePanel.add(groupAliasPanel);
		groupAliasPanel.setLayout(new BorderLayout(0, 0));
		groupAliasPanel.setBorder(border);

		lblNewLabel = new JLabel(" Group Alias:  ");
		groupAliasPanel.add(lblNewLabel, BorderLayout.WEST);

		groupAliasText = new JTextField();
		groupAliasPanel.add(groupAliasText, BorderLayout.CENTER);
		groupAliasText.setColumns(10);

		commentsText = new JTextPane();
		scrollPane = new JScrollPane(commentsText);
		scrollPane.setBackground(WHITE);
		scrollPane.setPreferredSize(new Dimension(8, 100));
		scrollPane.setBorder(new TitledBorder(border, "Comments", TitledBorder.LEADING, TitledBorder.TOP, null, null));
		headerPanel.add(scrollPane, BorderLayout.SOUTH);

		addComponentListener(new ComponentAdapter() 
		{
			@Override
			public void componentResized(ComponentEvent arg0) 
			{
				splitPane.setDividerLocation(0.5D);
			}
		});

		splitPane.setDividerLocation(0.5D);

		registerListeners();
	}

	private void registerListeners() 
	{
		toRightButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {
				if(availableCellModel.getSize() == 0)
				{
					return;
				}

				Object[] selectedUsers = allUsersList.getSelectedValues();
				if(null != selectedUsers)
				{
					for(Object userInfo:selectedUsers)
					{
						if(false == selectedCellModel.contains(userInfo))
						{
							selectedCellModel.addElement(userInfo);
						}
					}
				}
				SwingUtilities.updateComponentTreeUI(selectedUsersList);
				SwingUtilities.updateComponentTreeUI(allUsersList);
				if(availableCellModel.getSize() == 0)
				{
					toRightButton.setEnabled(false);
				}
				else
				{
					toRightButton.setEnabled(true);
				}
				toLeftButton.setEnabled(true);
				selectedUsersList.setSelectedIndex(-1);
				allUsersList.setSelectedIndex(-1);
			}
		});

		toLeftButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent actionEvent) {

				if(selectedCellModel.getSize() == 0)
				{
					return;
				}

				Object[] selectedUsers = selectedUsersList.getSelectedValues();
				if(null != selectedUsers)
				{
					for(Object userInfo:selectedUsers)
					{
						selectedCellModel.removeElement(userInfo);
						//availableCellModel.addElement(userInfo);
					}
				}
				SwingUtilities.updateComponentTreeUI(selectedUsersList);
				SwingUtilities.updateComponentTreeUI(allUsersList);
				if(selectedCellModel.getSize() == 0)
				{
					toLeftButton.setEnabled(false);
				}
				else
				{
					toLeftButton.setEnabled(true);
				}
				toRightButton.setEnabled(true);

				selectedUsersList.setSelectedIndex(-1);
				allUsersList.setSelectedIndex(1);
			}
		});

		okButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				selectedOption = SAVE_OPTION;
				setVisible(false);
			}
		});

		cancelButton.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent arg0) {
				selectedOption = CANCEL_OPTION;
				setVisible(false);
			}
		});

		groupNameText.addKeyListener(new KeyAdapter() 
		{
			@Override
			public void keyReleased(KeyEvent arg0) {
				String str = groupNameText.getText();
				if(null == str || true == str.isEmpty())
				{
					okButton.setEnabled(false);
				}
				else
				{
					okButton.setEnabled(true);
				}
			}
		});

		groupNameText.addFocusListener(new FocusListener() {

			@Override
			public void focusLost(FocusEvent arg0) {
				String str = groupNameText.getText();
				if(null == str || true == str.isEmpty())
				{
					okButton.setEnabled(false);
				}
				else
				{
					okButton.setEnabled(true);
				}

			}

			@Override
			public void focusGained(FocusEvent arg0) {
				String str = groupNameText.getText();
				if(null == str || true == str.isEmpty())
				{
					okButton.setEnabled(false);
				}
				else
				{
					okButton.setEnabled(true);
				}

			}
		});

	}

	private void setLocation() {
		Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
		setLocation((int)(size.getWidth()/2 - getWidth()/2),(int)( size.getHeight()/2 - getHeight()/2));
	}



	public void setAllItem(Set<ISVNItem> svnItems)
	{
		availableCellModel = null;
		selectedCellModel = null;

		availableCellModel = new DefaultListModel();
		selectedCellModel = new DefaultListModel();

		for(ISVNItem svnItem : svnItems)
		{
			availableCellModel.addElement(svnItem);
		}

		allUsersList.setModel(availableCellModel);
		selectedUsersList.setModel(selectedCellModel);
	}

	public void setSelectedItem(Set<ISVNItem> svnItems)
	{
		selectedCellModel = null;

		selectedCellModel = new DefaultListModel();

		for(ISVNItem svnItem : svnItems)
		{
			selectedCellModel.addElement(svnItem);
		}

		selectedUsersList.setModel(selectedCellModel);
	}

	public Set<ISVNItem> getSelectedItems()
	{
		Set<ISVNItem> infos = new HashSet<ISVNItem>(0);

		//If items are present in Selected section select all of them.
		int end = (selectedUsersList.getModel().getSize()-1);
		if(end >= 0)
		{
			selectedUsersList.setSelectionInterval(0, end);
		}


		if(selectedUsersList.getModel().getSize() > 0)
		{
			Object[] userInfos = selectedUsersList.getSelectedValues();
			if(null != userInfos)
			{
				for(Object userInfo : userInfos)
				{
					infos.add((ISVNItem)userInfo);
				}
			}
		}

		return infos;
	}

	public void setItemDescriptionTitle(String description,Icon icon)
	{
		svnItemDescription.setText(description);
		if(null != icon)
		{
			svnItemDescription.setIcon(icon);
		}
	}

	public int showDialog(ISVNItem targetItem)
	{
		this.targetItem = targetItem;
		selectedOption = CANCEL_OPTION;
		toRightButton.setEnabled(true);
		toLeftButton.setEnabled(true);
		groupNameText.requestFocus();
		setVisible(true);
		return selectedOption;
	}

	public static void main(String[] arg)
	{
		SVNGroup svnGroup = new SVNGroup("G","G");

		GroupDetailsEditorWindow contactSelectionDialog = new GroupDetailsEditorWindow();
		contactSelectionDialog.setItemDescriptionTitle(svnGroup.getTooltipText(),Utility.getImageIcon(IResources.LOC_ICN_GROUP_SMALL));

		Set<ISVNItem> map = new TreeSet<ISVNItem>();
		for(int nIndex = 1 ; nIndex<= 10 ; nIndex++)
		{
			svnGroup = new SVNGroup(String.format("G:%d",nIndex),String.format("G:%d",nIndex));
			map.add(svnGroup);
		}

		contactSelectionDialog.setAllItem(map);
		contactSelectionDialog.setVisible(true);
		System.out.println("Selected Items: " + contactSelectionDialog.getSelectedItems());
	}

	public JList getAllUsersList() {
		return allUsersList;
	}

	public JList getSelectedUsersList() {
		return selectedUsersList;
	}

	public JButton getOkButton() {
		return okButton;
	}

	public JButton getCancelButton() {
		return cancelButton;
	}

	public JButton getToLeftButton() {
		return toLeftButton;
	}

	public JButton getToRightButton() {
		return toRightButton;
	}

	public DefaultListModel getAvailableCellModel() {
		return availableCellModel;
	}

	public DefaultListModel getSelectedCellModel() {
		return selectedCellModel;
	}

	public JScrollPane getAvailablePane() {
		return availablePane;
	}

	public JLabel getSvnItemDescription() {
		return svnItemDescription;
	}

	public JTextField getGroupNameText() {
		return groupNameText;
	}

	public ISVNItem getTargetItem() {
		return targetItem;
	}

	public void setTargetItem(ISVNItem targetItem) {
		this.targetItem = targetItem;
	}

	/**
	 * @return the groupAliasText
	 */
	 public JTextField getGroupAliasText() {
		 return groupAliasText;
	 }

	 /**
	  * @return the commentsText
	  */
	 public JTextPane getCommentsText() {
		 return commentsText;
	 }


}
